const OutboundDocument = require('../models/OutboundDocument');
const Goods = require('../models/Goods');

class OutboundController {
  // 获取所有出库单据
  static getAllOutboundDocuments(req, res) {
    OutboundDocument.findAll((err, documents) => {
      if (err) {
        return res.status(500).json({
          success: false,
          message: '获取出库单据列表失败',
          error: err.message
        });
      }
      
      res.json({
        success: true,
        data: documents
      });
    });
  }

  // 根据ID获取出库单据
  static getOutboundDocumentById(req, res) {
    const { id } = req.params;
    
    OutboundDocument.findById(id, (err, document) => {
      if (err) {
        return res.status(500).json({
          success: false,
          message: '查询出库单据失败',
          error: err.message
        });
      }
      
      if (!document) {
        return res.status(404).json({
          success: false,
          message: '出库单据未找到'
        });
      }
      
      res.json({
        success: true,
        data: document
      });
    });
  }

  // 创建新出库单据
  static createOutboundDocument(req, res) {
    const { goodsId, customer, quantity, expectedPickupDate, operator, notes } = req.body;
    
    // 验证必填字段
    if (!goodsId || !customer) {
      return res.status(400).json({
        success: false,
        message: '货物ID和客户为必填项'
      });
    }
    
    // 验证货物是否存在且库存充足
    Goods.findById(goodsId, (err, goods) => {
      if (err) {
        return res.status(500).json({
          success: false,
          message: '验证货物失败',
          error: err.message
        });
      }
      
      if (!goods) {
        return res.status(400).json({
          success: false,
          message: '指定的货物不存在'
        });
      }
      
      if (goods.quantity < (quantity || 0)) {
        return res.status(400).json({
          success: false,
          message: '货物库存不足'
        });
      }
      
      const newDocument = new OutboundDocument(
        null,
        goodsId,
        customer,
        quantity || 0,
        expectedPickupDate || new Date(),
        null,
        'pending',
        operator || '',
        notes || '',
        new Date()
      );
      
      // 保存出库单据
      newDocument.save((err, result) => {
        if (err) {
          return res.status(500).json({
            success: false,
            message: '创建出库单据失败',
            error: err.message
          });
        }
        
        res.status(201).json({
          success: true,
          message: '出库单据创建成功',
          data: { id: result.id, ...newDocument }
        });
      });
    });
  }

  // 更新出库单据状态
  static updateOutboundDocumentStatus(req, res) {
    const { id } = req.params;
    const { status, pickupDate } = req.body;
    
    OutboundDocument.findById(id, (err, document) => {
      if (err) {
        return res.status(500).json({
          success: false,
          message: '查询出库单据失败',
          error: err.message
        });
      }
      
      if (!document) {
        return res.status(404).json({
          success: false,
          message: '出库单据未找到'
        });
      }
      
      // 创建出库单据对象
      const docObj = new OutboundDocument(
        document.id,
        document.goods_id,
        document.customer,
        document.quantity,
        document.expected_pickup_date,
        document.actual_pickup_date,
        document.status,
        document.operator,
        document.notes,
        document.created_at
      );
      
      if (status === 'completed') {
        docObj.complete(pickupDate || new Date(), (err, result) => {
          if (err) {
            return res.status(500).json({
              success: false,
              message: '完成出库操作失败',
              error: err.message
            });
          }
          
          // 更新货物库存
          Goods.findById(document.goods_id, (err, goods) => {
            if (err) {
              return res.status(500).json({
                success: false,
                message: '查询货物失败',
                error: err.message
              });
            }
            
            if (!goods) {
              return res.status(400).json({
                success: false,
                message: '关联的货物不存在'
              });
            }
            
            const goodsObj = new Goods(
              goods.id,
              goods.name,
              goods.sku,
              goods.quantity,
              goods.location,
              goods.status,
              goods.batch_number,
              goods.expiry_date,
              goods.created_at
            );
            
            goodsObj.checkout(document.quantity, (err, result) => {
              if (err) {
                return res.status(500).json({
                  success: false,
                  message: '更新货物库存失败',
                  error: err.message
                });
              }
              
              res.json({
                success: true,
                message: '出库单据状态更新成功，货物库存已更新',
                data: docObj
              });
            });
          });
        });
      } else {
        docObj.updateStatus(status, (err, result) => {
          if (err) {
            return res.status(500).json({
              success: false,
              message: '更新出库单据状态失败',
              error: err.message
            });
          }
          
          res.json({
            success: true,
            message: '出库单据状态更新成功',
            data: docObj
          });
        });
      }
    });
  }

  // 取消出库单据
  static cancelOutboundDocument(req, res) {
    const { id } = req.params;
    const { reason } = req.body;
    
    OutboundDocument.findById(id, (err, document) => {
      if (err) {
        return res.status(500).json({
          success: false,
          message: '查询出库单据失败',
          error: err.message
        });
      }
      
      if (!document) {
        return res.status(404).json({
          success: false,
          message: '出库单据未找到'
        });
      }
      
      // 创建出库单据对象
      const docObj = new OutboundDocument(
        document.id,
        document.goods_id,
        document.customer,
        document.quantity,
        document.expected_pickup_date,
        document.actual_pickup_date,
        document.status,
        document.operator,
        document.notes,
        document.created_at
      );
      
      docObj.cancel(reason || '无原因', (err, result) => {
        if (err) {
          return res.status(500).json({
            success: false,
            message: '取消出库单据失败',
            error: err.message
          });
        }
        
        res.json({
          success: true,
          message: '出库单据已取消',
          data: docObj
        });
      });
    });
  }

  // 查询出库数据
  static queryOutbound(req, res) {
    // 获取查询参数
    const {
      materialName,
      materialCode,
      location,
      aisle,
      row,
      column,
      level,
      endEquipment,
      aisleNumber
    } = req.query;
    
    // 构建SQL查询语句
    let sql = `
      SELECT 
        g.id,
        g.location,
        g.pallet_id as pallet,
        g.sku as materialCode,
        g.name as materialName,
        g.specification,
        g.unit,
        g.quantity
      FROM goods g
      WHERE g.status = 'inStock'
    `;
    
    const params = [];
    
    // 添加查询条件
    if (materialName) {
      sql += ' AND g.name LIKE ?';
      params.push(`%${materialName}%`);
    }
    
    if (materialCode) {
      sql += ' AND g.sku LIKE ?';
      params.push(`%${materialCode}%`);
    }
    
    if (location) {
      sql += ' AND g.location LIKE ?';
      params.push(`%${location}%`);
    }
    
    // 根据货位号解析巷道、排、列、层进行查询
    if (aisle || row || column || level) {
      // 这里可以根据需要添加更复杂的货位号解析查询
      if (aisle) {
        sql += ' AND g.location LIKE ?';
        params.push(`%-${aisle}-%`);
      }
    }
    
    sql += ' ORDER BY g.id DESC';
    
    // 执行查询
    const db = require('../config/database');
    db.all(sql, params, (err, rows) => {
      if (err) {
        return res.status(500).json({
          success: false,
          message: '查询失败',
          error: err.message
        });
      }
      
      res.json({
        success: true,
        data: rows
      });
    });
  }
}

module.exports = OutboundController;